//
//  SICPSDKService.m
//  test1
//
//  Created by Piccolo on 2017/4/19.
//  Copyright © 2017年 Piccolo. All rights reserved.
//

#import "SICPSDKService.h"
#import "SICPSDKBlueToothTool.h"
#import "SICPSDKSendRequest.h"

#define LOOP_LIMITED_MILLISECOND 5000

static NSMutableDictionary *dic;
static NSMutableDictionary *detailDic;
static NSMutableDictionary *activeReportDetailDic;

static SICPSDKResultInfo *smart_it_camping_light_result_info;
static SICPSDKActiveReportInfo *smart_it_camping_light_active_result_info;
static NSString *current_select;
static NSString *current_connected_peripheral;
static NSDictionary *service_dic;
static BOOL is_init_sdk = NO;
static BOOL is_connected_peripheral = NO;
static BOOL is_register = NO;

@interface SICPSDKService ()
@property (nonatomic, strong) NSMutableArray *ultrHistoryInfoArray;
@property (nonatomic, strong) NSMutableArray *tempHistoryInfoArray;
@property (nonatomic, strong) NSMutableArray *humiHistoryInfoArray;
@property (nonatomic, strong) NSMutableArray *presHistoryInfoArray;
@property (nonatomic, strong) NSMutableArray *heigHistoryInfoArray;
@property (nonatomic, assign) NSInteger day;
@property (atomic, strong) NSMutableDictionary *activeReportDetailDic;
@property (nonatomic, strong) NSLock *lock;
@end

@implementation SICPSDKService{
    
    

}

+ (void)initSDK{
//    [SICPSDKService sharedManager].
    current_select = @"init_sdk";
    is_init_sdk = YES;
    is_connected_peripheral = NO;
    is_register = NO;
    [self initFeedbackInfo];
    detailDic = [[NSMutableDictionary alloc] init];
    [SICPSDKService sharedManager].activeReportDetailDic = [NSMutableDictionary new];
    [detailDic setObject:SDK_VERSION forKey:@"sdk_version"];
    [detailDic setObject:SDK_RELEASE_TIME forKey:@"sdk_release_time"];
    [self updateLogWithSuccess];
    
}

//实现单例方法


+ (instancetype)sharedManager{
    
    static SICPSDKService *tool = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        tool = [[self alloc] init];
    });
    return tool;
    
}

+ (void)initFeedbackInfo{
    dic = [[NSMutableDictionary alloc] init];
    smart_it_camping_light_result_info = [[SICPSDKResultInfo alloc] init];
}

+ (void)initActiveFeedbackInfo{
    if (!smart_it_camping_light_active_result_info) {
        smart_it_camping_light_active_result_info = [[SICPSDKActiveReportInfo alloc] init];
    }
}

+ (void)destroyBle{
    
    current_select = @"destroy";
    
    [self initFeedbackInfo];
    
    if (is_init_sdk){
        [[SICPSDKBlueToothTool sharedManager] destroyTheKey];
        is_init_sdk = NO;
        [self updateLogWithSuccess];
        
    }
    else{
        [dic setObject:@"empty_ble_sdk" forKey:@"error"];
        [self updateLogWithFailed];
    }
    
    
}

+ (void)setDelegate:(id)delegate{
    [SICPSDKService sharedManager].delegate = delegate;
}

+ (void)initBlueToothManager{
    
    current_select = @"init_ble_manager";
    [[SICPSDKBlueToothTool sharedManager] initBlueToothManager];
}

+ (void)startScan{
    
//    is_init_sdk = NO;
    
    [[SICPSDKBlueToothTool sharedManager] startScan];
    
}

+ (void)stopScan{
    
//    is_init_sdk = NO;
    
    [[SICPSDKBlueToothTool sharedManager] stopScan];
    
}

+ (void)disConnectBle {
    
    current_select = @"disconnect";
    
    [SICPSDKSendRequest disconnectBle];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        NSString *disconnectedPeripheral = [[SICPSDKBlueToothTool sharedManager] getDisconnectedKey];
        [self initFeedbackInfo];
        if ([SICPSDKCommon judgeExist:disconnectedPeripheral]){
            //            [dic setObject:@"successful" forKey:@"disconnect_ble"];
            is_connected_peripheral = NO;
            is_register = NO;
            [self updateLogWithSuccess];
        }
        else {
            
            [dic setObject:@"disconnect_ble_failed" forKey:@"error"];
            [self updateLogWithFailed];
            return;
        }
        
        
    });

    
}

+ (void)updateLogWithFailed{
    smart_it_camping_light_result_info.feedBackDic = dic;
    smart_it_camping_light_result_info.feedBackState = NO;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateLogWithCurrentSelect];
        //        [[SICPSDKService sharedManager].delegate requestResultInfo:SICPSDKResultInfo];
    });
}

+ (void)updateLogWithSuccess{
    smart_it_camping_light_result_info.feedBackDic = dic;
    smart_it_camping_light_result_info.feedBackState = YES;
    if ([SICPSDKCommon judgeExist:detailDic]){
        smart_it_camping_light_result_info.detailDic = [detailDic copy];
        [detailDic removeAllObjects];
    }
    if ([SICPSDKCommon judgeExist:[SICPSDKService sharedManager].activeReportDetailDic]) {
        smart_it_camping_light_active_result_info.detailDic = [[SICPSDKService sharedManager].activeReportDetailDic copy];
        [[SICPSDKService sharedManager].activeReportDetailDic removeAllObjects];
    }
    
    //    [SICPSDKSendRequest updateLog:SICPSDKResultInfo];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateLogWithCurrentSelect];
    });

}

+ (void)updateLogWithCurrentSelect{
    if ([current_select isEqualToString: @"init_sdk"]){
        [[SICPSDKService sharedManager].delegate requestInitSdkResultInfo:smart_it_camping_light_result_info];
    }
    else if ([current_select isEqualToString: @"connect"]){
        [[SICPSDKService sharedManager].delegate requestConnectResultInfo:smart_it_camping_light_result_info];
    }
    else if ([current_select isEqualToString: @"destroy"]){
        [[SICPSDKService sharedManager].delegate requestDestroyResultInfo:smart_it_camping_light_result_info];
    }
    else if ([current_select isEqualToString: @"init_ble_manager"]){
        [[SICPSDKService sharedManager].delegate requestInitBleManagerResultInfo:smart_it_camping_light_result_info];
    }
    else if ([current_select isEqualToString: @"disconnect"]){
        if ([SICPSDKCommon delegateExist:[SICPSDKService sharedManager].delegate delegate:@protocol(SILightDelegate) selector:@selector(requestDisconnectResultInfo:)]) {
            [[SICPSDKService sharedManager].delegate requestDisconnectResultInfo:smart_it_camping_light_result_info];
        }
    }
    
    else if ([current_select isEqualToString: @"active_report"]){
        [[SICPSDKService sharedManager].delegate requestActiveReport:smart_it_camping_light_active_result_info];
    }
    else if ([current_select isEqualToString: @"device_info"]){
        [[SICPSDKService sharedManager].delegate requestDeviceResultInfo:smart_it_camping_light_result_info];
    }
    
}

//+ (void)connectBlueTooth:(id)delegate andPeripheral:(CBPeripheral *)per{
+ (void)connectBlueTooth:(SICPSDKPeripheral *)per{
    
    current_select = @"connect";
    //    [SICPSDKService sharedManager].delegate = delegate;
    [self initFeedbackInfo];
    detailDic = [[NSMutableDictionary alloc] init];
    if (is_init_sdk){
        
        [[SICPSDKBlueToothTool sharedManager] connectBle:per];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            
            current_connected_peripheral = [[SICPSDKBlueToothTool sharedManager] getConnectedKey];
            
            if (current_connected_peripheral){
                [detailDic setObject:current_connected_peripheral forKey:@"connect peripheral"];
                service_dic = [[SICPSDKBlueToothTool sharedManager] getValueServiceDic];
                
                is_connected_peripheral = YES;
                
            }
            else{
                [dic setObject:@"missing_peripheral" forKey:@"error"];
                [self updateLogWithFailed];
            }
            
            [self registerKey];
            
        });
    }
    else{
        [dic setObject:@"empty_ble_sdk" forKey:@"error"];
        [self updateLogWithFailed];
        
    }
}



+ (void)registerKey{
    //    current_select = @"register";
    if (!is_init_sdk){
        [dic setObject:@"empty_ble_sdk" forKey:@"error"];
        [self updateLogWithFailed];
        return;
    }
    if (!is_connected_peripheral){
        [dic setObject:@"no_peripheral_connected" forKey:@"error"];
        [self updateLogWithFailed];
        return;
    }
    if ([SICPSDKCommon judgeExist:current_connected_peripheral]) {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

            CBService *readService = [service_dic objectForKey:@"read_service"];
            CBPeripheral *peripheral = [service_dic objectForKey:@"peripheral"];
            CBService *writeService = [service_dic objectForKey:@"write_service"];
            for (CBCharacteristic *characteristic in readService.characteristics) {
                
                NSLog(@"@224%@----%@",readService.UUID,characteristic.UUID);
                
                if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:READ_CHARA]]) {
                    
                    NSLog(@"@296获取蓝牙读交互通道%@成功", READ_CHARA);
                    //                    [dic setObject:@"successful" forKey:@"get_ff02"];
                    [SICPSDKBlueToothTool sharedManager].readCharacteristic = characteristic;
                    [[SICPSDKBlueToothTool sharedManager].smartItPeripheral.peripheral setNotifyValue:YES forCharacteristic:characteristic];
                    [[SICPSDKBlueToothTool sharedManager].smartItPeripheral.peripheral readValueForCharacteristic:characteristic];
                    [self updateLogWithSuccess];
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                        
                        [SICPSDKSendRequest startDetectActiveReportingValueOfCharacteristic];
                        
                    });
                }
            }
            
            for (CBCharacteristic *characteristic in writeService.characteristics) {
                
                NSLog(@"@224%@----%@",writeService.UUID,characteristic.UUID);
                
                if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:WRITE_CHARA]]) {
                    [SICPSDKBlueToothTool sharedManager].writeCharacteristic = characteristic;
                    NSLog(@"@290获取蓝牙写交互通道%@成功", WRITE_CHARA);
                    [SICPSDKSendRequest setPeripheralAndCharacteristic:peripheral andCharacteristic:characteristic];
                }
            }
        });
    }
}

+ (void)manageActiveReportingValueOfCharacteristic:(NSData *)activeReportingValue{
    
    if ([self checkSdkConReg]) {
        [self initActiveFeedbackInfo];
        [SICPSDKService sharedManager].activeReportDetailDic = [[NSMutableDictionary alloc] init];
        [[SICPSDKService sharedManager].activeReportDetailDic setObject:@"active_report" forKey:@"detail_info_type"];
        dic = [[NSMutableDictionary alloc] init];
        current_select = @"active_report";
        Byte *ddd = (Byte *)activeReportingValue.bytes;
        if (ddd[0] == 0x10) {
            NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] init];
            [tempDic setObject:activeReportingValue forKey:@"auto_basic_report_data"];
            [SICPSDKService sharedManager].activeReportDetailDic = tempDic;
            [self updateLogWithSuccess];
        }
//        if (ddd[0] == 0x11) {
//            NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] init];
//            [tempDic setObject:activeReportingValue forKey:@"auto_basic_report_data"];
//            [SICPSDKService sharedManager].activeReportDetailDic = tempDic;
//            [self updateLogWithSuccess];
//        } else if (ddd[0] == 0x10) {
////            NSLog(@"@这里收到2");
//            NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] init];
//            [tempDic setObject:activeReportingValue forKey:@"auto_current_report_data"];
//            [SICPSDKService sharedManager].activeReportDetailDic = tempDic;
//            [self updateLogWithSuccess];
//        }
        
    }
    
}


+ (BOOL)checkSdkConReg{
    [self initFeedbackInfo];
    if (!is_init_sdk){
        [dic setObject:@"empty_ble_sdk" forKey:@"error"];
        [self updateLogWithFailed];
        return NO;
    }
    if (!is_connected_peripheral){
        [dic setObject:@"no_peripheral_connected" forKey:@"error"];
        [self updateLogWithFailed];
        return NO;
    }
    return is_init_sdk && is_connected_peripheral;
}

+ (SICPSDKPeripheral *)getCurrentBle{
    return [SICPSDKBlueToothTool sharedManager].smartItPeripheral;
}

+ (CBPeripheralState)getCurrentBleState{
    return [SICPSDKBlueToothTool sharedManager].smartItPeripheral.peripheral.state;
}

+ (BOOL)getManagerScanning {
    return [SICPSDKCommon managerIsScanning:[SICPSDKBlueToothTool sharedManager].manager defBool:NO];
}

+ (void)sendSettingDeviceTime {
    if ([self checkSdkConReg]) {
        [self initFeedbackInfo];
        [SICPSDKSendRequest sendSettingDeviceTime];
    }
}

+ (void)sendSettingBasicInfoFromLightInfo:(SILightInfo *)lightInfo {
    if ([self checkSdkConReg]) {
        [self initFeedbackInfo];
        [SICPSDKSendRequest sendSettingBasicInfoFromLightInfo:lightInfo];
    }
}

+ (void)sendAdditionalCommandFromLightAddtionalInfo:(SILightAddtionalInfo *)lightAddtionalInfo {
    if ([self checkSdkConReg]) {
        [self initFeedbackInfo];
        [SICPSDKSendRequest sendAdditionalCommandFromLightAddtionalInfo:lightAddtionalInfo];
    }
}

+ (void)sendSettingDeviceName:(NSString *)deviceName {
    
    if ([self checkSdkConReg]) {
        [self initFeedbackInfo];
        [SICPSDKSendRequest sendSettingDeviceName:deviceName];
    }
}

+ (void)sendSettingAwakenInfoFromLightInfo:(SILightInfo *)lightInfo {
    
    if ([self checkSdkConReg]) {
        [self initFeedbackInfo];
        [SICPSDKSendRequest sendSettingAwakenInfo:lightInfo];
    }
}
@end
